<template>
  <div>
    <mt-header title="选择收货地址" :fixed="true">
      <router-link style="text-decoration: none;" to="/index" slot="left">
        <span class="iconfont icon-go-back"></span>
      </router-link>
      <mt-button v-if="$store.state.token" class="font" slot="right" @click="$router.push('/editaddress')">新增地址</mt-button>
    </mt-header>
    <div class="search-box">
      <p class="choose ellipsis base-font-size" @click="choosePosition">{{text}}</p>
      <span class="iconfont icon-sanjiaoxia" @click="choosePosition"></span>
      <div style="position: relative;">
        <span class="iconfont icon-sousuo"></span>
        <input class="address-inp" type="text" placeholder="请输入地址"v-model="addr"/>
      </div>
    </div>
    <div class="query-box" v-if="queryList.length !== 0" >
      <div class="query-item flex-row-sb-center" v-for="item in queryList" :key="item.id" @click="getPeripheral(item)">
        <div style="width: 80%;">
          <p class="title ellipsis"><strong>{{item.name}}</strong></p>
          <p class="addr ellipsis">{{item.address}}</p>
        </div>
        <span class="distance">{{item.distance}}</span>
      </div>
      <p class="not-find-addr base-font-size">找不到地址？</p>
      <p class="hint">请尝试只输入小区、写字楼或学校名</p>
      <p class="hint">详细地址（如门牌号）可稍后输入</p>
    </div>
    <div class="not-find-box" v-else-if="addr.length !== 0 && queryList.length === 0">
      <img class="not-find-img" src="https://fuss10.elemecdn.com/6/87/4efda8c6bf4734d39faf86fe190c3gif.gif" />
      <p class="no-result">没有搜索结果</p>
      <p class="change-keyword">换个关键字试试</p>
    </div>
    <div v-if="$store.state.token">
      <p class="nav-title">当前地址</p>
      <div v-if="addressList.length > 0" style="border: none;" class="box flex-row-sb-center">
        <p class="current-addr">{{currentAddr}}</p>
        <p @click="rePosi">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" :class="['re-posi-svg', reposi?'rotate': '']">
            <g fill="none" fill-rule="evenodd">
              <circle cx="7.5" cy="7.5" r="7" stroke="#2395FF"></circle>
              <path fill="#2395FF" d="M7 0h1v5H7zM7 10h1v5H7zM10 7h5v1h-5zM0 7h5v1H0z"></path>
            </g>
          </svg>
          <span class="re-posi">重新定位</span>
        </p>
      </div>
      <p class="nav-title">收货地址</p>
      <div class="box receipt-addr" v-for="item in addressList" :key="item.id">
        <p style="margin: 10px 0 0;">
          <span class="consignee-name">{{item.name}}</span>
          <span class="consignee-tel">{{item.phone}}</span>
        </p>
        <p class="consignee-addr">{{item.address}}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { getDetailAddress1, selectPosi, getDetailAddress2, getAddrShopInfo, getMyAddress, rePosition } from '@/api/elm-data'
export default {
  name: 'get-position',
  data() {
    return {
      addr: '',
      text: '选择地址',
      longitude: '',
      latitude: '',
      currentAddr: '',
      queryList: [],
      addressList: [],
      reposi: false
    }
  },
  methods: {
    choosePosition() {
      this.$router.push('/chooseposition')
    },
    async getPeripheral(info) {
      const { data } = await selectPosi(info.latitude, info.longitude)
      const { data: res } = await getAddrShopInfo(info.latitude, info.longitude)
      window.sessionStorage.setItem('index-data', JSON.stringify({data, res}))
      window.sessionStorage.setItem('posi-name', info.name)
      window.sessionStorage.setItem('position', 'success')
      window.sessionStorage.setItem('city_id', info.city_id)
      window.sessionStorage.setItem('Geo', JSON.stringify({latitude: info.latitude, longitude: info.longitude}))
      this.$router.replace({name: 'index', query: {}})
    },
    rePosi() {
      this.reposi = true
      let f = true
      const interval = setInterval(async () => {
        if(f) {
          f = false
          try {
            const { data } = await rePosition({
              latitude: this.latitude,
              longitude: this.longitude
            })
            console.log(data)
            if(data&&data.name) {
              this.currentAddr = data.name
            }else {
              this.currentAddr = data.city
            }
            this.reposi = false
            clearInterval(interval)
          }catch(e) {
            this.$toast('定位失败', 'center')
          }
        }
      }, 1000)
    }
  },
  async created() {
    const selCity =  JSON.parse(window.sessionStorage.getItem('select-city'))
    const geo =  JSON.parse(window.sessionStorage.getItem('Geo'))
    this.longitude = (selCity&&selCity.longitude) || geo?.longitude || ''
    this.latitude = (selCity&&selCity.latitude) || geo?.latitude || ''
    this.text =  window.sessionStorage.getItem('posi-name') || (selCity&&selCity.name) || '选择地址'
    if(window.sessionStorage.getItem('position') !== 'failed' &&!this.$store.state.token) {
      const { data } = await getDetailAddress1(this.latitude, this.longitude, this.addr)
      this.queryList = data
    }
    if(this.$store.state.token) {
      const { data } = await getMyAddress(window.sessionStorage.getItem('USER_ID'))
      this.addressList = data
      this.currentAddr = this.addressList[0].address
    }
  },
  watch: {
    async addr() {
      if(this.addr === '') return this.queryList = []
      if(window.sessionStorage.getItem('position') !== 'failed') {
        const { data } = await getDetailAddress1(this.latitude, this.longitude, this.addr)
        this.queryList = data
      }else {
        const { data } = await getDetailAddress2(this.addr)
        this.queryList = data
      }
    }
  }
}
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    margin-top: 70px;
    padding: 10px 20px;
    background-color: #fff;
    align-items: center;
  }
  .choose {
    width: 80px;
  }
  .address-inp {
    position: relative;
    height: 60px;
    width: 500px;
    margin-left: 20px;
    padding-left: 37px;
    background-color: #f5f5f5;
    border: none;
    font-size: 28px;
  }
  .icon-sousuo {
    position: absolute;
    font-size: 28px;
    left: 30px;
    top: 17px;
    z-index: 9;
  }
  .icon-sanjiaoxia {
    font-size: 18px;
  }
  .title {
    margin-bottom: 0;
    font-size: 30px;
  }
  .query-box {
    height: calc(100vh - 174px);
    padding-bottom: 20px;
    background-color: #fff;
    overflow: scroll;
    box-sizing: border-box;
  }
  .query-item {
    padding: 10px 20px;
    align-items: baseline;
    border-bottom: 1px solid #CCCCCC;
  }
  .addr {
    margin: 0;
    font-size: 22px;
  }
  .distance {
    font-size: 24px;
  }
  .not-find-addr {
    margin: 40px 0 0;
    text-align: center;
    color: #818181;
  }
  .hint {
    margin: 0;
    text-align: center;
    color: #999;
  }
  .not-find-box {
    margin-top: 300px;
    text-align: center;
  }
  .not-find-img {
    width: 500px;
  }
  .no-result {
    margin: 0;
    font-size: 28px;
    color: #565656;
  }
  .change-keyword {
    margin: 0;
    font-size: 20px;
    color: #999;
  }
  .box {
    padding: 5px 15px;
    background-color: #fff;
    border-bottom: 1px solid #efefef;
  }
  .nav-title {
    padding-left: 20px;
    font-size: 26px;
    color: #797979;
  }
  .current-addr {
    font-size: 30px;
    font-weight: 600;
  }
  .re-posi {
    padding-left: 10px;
    font-size: 28px;
    color: #0097FF;
  }
  .rotate {
    animation: rotate .3s linear infinite;
  }
  .re-posi-svg {
    height: 28px;
  }
  @keyframes rotate{
    100% {
      transform: rotate(180deg);
    }
  }
  .consignee-name {
    margin: 5px 0;
    font-size: 30px;
    font-weight: 600;
    color: #313131;
  }
  .consignee-addr {
    margin: 10px 0;
    font-size: 24px;
    color: #313131;
  }
  .consignee-tel {
    padding-left: 15px;
    font-size: 22px;
    color: #7f7f7f;
  }
</style>
